package StudyCode.summary.zipfile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.GZIPOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CompressStringWithGZIP {
	public static byte[] compress(String string) throws IOException {
		byte[] blockcopy = ByteBuffer.allocate(4)
				.order(java.nio.ByteOrder.LITTLE_ENDIAN)
				.putInt(string.length()).array();
		ByteArrayOutputStream os = new ByteArrayOutputStream(
				string.length());
		GZIPOutputStream gos = new GZIPOutputStream(os);
		gos.write(string.getBytes());
		gos.close();
		os.close();
		byte[] compressed = new byte[4 + os.toByteArray().length];
		System.arraycopy(blockcopy, 0, compressed, 0, 4);
		System.arraycopy(os.toByteArray(), 0, compressed, 4,
				os.toByteArray().length);
		return compressed;
	}
}
